# 这是一个示例 Python 脚本。

# 按 Shift+F10 执行或将其替换为您的代码。
# 按 双击 Shift 在所有地方搜索类、文件、工具窗口、操作和设置。

import _thread
import time
import machine
import wifi
from WS2812_LED import WS2812_LED
from umqtt.simple import MQTTClient
from DHT11 import DHT11

# 串口2和语音通信
uart2 = machine.UART(2, 115200)
# 串口0和stc51通信
uart0 = machine.UART(0, 115200)
pin15 = machine.Pin(15, machine.Pin.OUT)
# MQTT 配置
client = None
mqtt_broker = "192.168.203.52"
mqtt_port = 1883
client_id = "esp32_client"
temp_topic_sub = b"humidity_temp"
led_topic_sub = b"rainbow_led_ctl"
security_system_sub = b"security_system"
tv_ctl_sub = b"tv_ctl"
fan_ctl_sub = b"fan_ctl"


def rainbow_on():
    strip = WS2812_LED(pin15, 12)
    for _ in range(5):
        strip.rainbow_cycle()


def light_on():
    strip = WS2812_LED(pin15, 12)
    strip.fill(255, 255, 255)
    strip.show()


def light_off():
    strip = WS2812_LED(pin15, 12)
    strip.fill(0, 0, 0)
    strip.show()


def mqtt_callback(topic, msg):
    # print("收到消息:", topic.decode(), msg.decode())
    topic_ = topic.decode()
    msg_ = msg.decode()
    if topic_ == "rainbow_led_ctl" and msg_ == "on":
        uart0.write("A")
    if topic_ == "rainbow_led_ctl" and msg_ == "off":
        uart0.write("B")
    #     开门锁
    if topic_ == "security_system" and msg_ == "on":
        uart2.write("C")
    #     关门锁
    if topic_ == "security_system" and msg_ == "off":
        uart2.write("D")
    #     电视开
    if topic_ == "tv_ctl" and msg_ == "on":
        uart2.write("E")
    #     电视关
    if topic_ == "tv_ctl" and msg_ == "off":
        uart2.write("F")
    #     风扇开
    if topic_ == "fan_ctl" and msg_ == "on":
        uart2.write("G")
    #     风扇关
    if topic_ == "fan_ctl" and msg_ == "off":
        uart2.write("H")
    #     动画1
    if topic_ == "tv_movie1" and msg_ == "on":
        uart2.write("I")
    #     动画2
    if topic_ == "tv_movie2" and msg_ == "on":
        uart2.write("J")


def deal_uart_2(*args, **kwargs):
    while True:
        data = uart2.read()
        if data is not None:
            data_ = data.decode().strip()
            print("串口2收到的数据", data_)
            # 处理温湿度
            if "th" in data_:
                th_data = data_.split(":")
                if th_data[0] == "th" and client is not None:
                    client.publish(temp_topic_sub, data_)
            if data_ == "light_on":
                light_on()
            if data_ == "light_off":
                light_off()
        time.sleep(1)


def deal_uart_0(*args, **kwargs):
    while True:
        data = uart0.read()
        if data is not None:
            data0 = data.decode().strip()
            print("串口0收到的数据", data0)
        time.sleep(1)


def deal_mqtt_msg(*args, **kwargs):
    global client
    wifi.connect_wifi()
    print("正在连接 MQTT 服务器...")
    time.sleep(2)
    client = MQTTClient(client_id, mqtt_broker, port=mqtt_port)
    client.set_callback(mqtt_callback)

    try:
        client.connect()
        client.subscribe(led_topic_sub)
        client.subscribe(temp_topic_sub)
        client.subscribe(security_system_sub)
        client.subscribe(tv_ctl_sub)
        client.subscribe(fan_ctl_sub)
        print("MQTT 服务器已连接")
    except Exception as e:
        print("MQTT 连接错误:", e)
        return

    while True:
        client.check_msg()  # 检查订阅消息
        time.sleep(1)


def deal_dht11(*args, **kwargs):
    dht_sensor = DHT11(21)
    while True:
        # 读取数据
        success, humidity, temperature = dht_sensor.read()
        if client is not None:
            print("client.publish")
            client.publish(b"humidity_temp", f"60,30")
        if success:
            print(f"湿度: {humidity}%  温度: {temperature}°C")
        else:
            print("读取失败，请检查连接")

        # 间隔3秒读取一次
        time.sleep(3)


thread_1 = _thread.start_new_thread(deal_uart_2, (1,))
thread_2 = _thread.start_new_thread(deal_mqtt_msg, (2,))
# thread_3 = _thread.start_new_thread(deal_dht11, (3,))
thread_4 = _thread.start_new_thread(deal_uart_0, (4,))
